package com.rxt.thermopro.widget

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.provider.MediaStore
import android.util.AttributeSet
import android.util.Log
import androidx.constraintlayout.widget.ConstraintLayout


class ShareImageLayout@JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    /**
     * 将bitmap保存为JPG格式的图片
     */
    fun saveImage(): String? {
        //View是你需要绘画的View
        val width = width
        val height = height
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        //如果不设置canvas画布为白色，则生成透明 canvas.drawColor(Color.WHITE);
        draw(canvas)

        // 保存图片
        var url: String? = null
        try {
//            File file = new File(Environment.getExternalStorageDirectory(),
//                    "share_image_" + SystemClock.currentThreadTimeMillis() + ".jpg");
//            url = file.getAbsolutePath();
//            FileOutputStream stream = new FileOutputStream(file);
//            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
//            stream.close();

            //将生成的Bitmap插入到手机的图片库当中，获取到图片路径
            url = MediaStore.Images.Media.insertImage(
                context.contentResolver,
                bitmap, null, null
            )
            //及时回收Bitmap对象，防止OOM
            if (!bitmap.isRecycled) {
                bitmap.recycle()
            }
            Log.d("ShareImageLayout-->", "保存成功，已经保存到$url")
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("ShareImageLayout-->", "保存失败$e")
        }
        return url
    }


    /**
     * 将bitmap保存为JPG格式的图片
     */
    fun getImageBitmap(): Bitmap? {
        //View是你需要绘画的View
        val width = width
        val height = height
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        //如果不设置canvas画布为白色，则生成透明 canvas.drawColor(Color.WHITE);
        draw(canvas)
        return bitmap
    }

}